package fr.utbm.gi.vi51.project.formations;

import javax.vecmath.Point2d;
import javax.vecmath.Vector2d;

import fr.utbm.gi.vi51.framework.util.GeometryUtil;

public class FormationSlot implements Comparable<FormationSlot> {

	private final FormationSlot parent;
	private FormationBody body;
	private int index;
	private final Vector2d relativePosition;
	private final float relativeRotation;

	/**
	 * Constructor for leader slot.
	 * 
	 * @param body
	 */
	public FormationSlot(FormationBody body) {
		this.parent = null;
		this.body = body;
		this.index = 0;
		this.relativePosition = new Vector2d(0, 0);
		this.relativeRotation = 0;
	}

	/**
	 * Constructor for follower slot.
	 */
	public FormationSlot(FormationSlot parent, FormationBody body, int index, double relativeX, double relativeY,
			float relativeRotation) {
		this.parent = parent;
		this.body = body;
		this.index = index;
		this.relativePosition = new Vector2d(relativeX, relativeY);
		this.relativeRotation = relativeRotation;
	}

	public float getGlobalOrientation() {
		float result;
		if (this.parent != null) {
			result = this.parent.getGlobalOrientation();
		} else {
			result = this.body.getGlobalOrientation();
		}
		result += this.relativeRotation;
		return result;
	}

	public Point2d getGlobalPosition() {
		Vector2d vector = new Vector2d();
		Point2d point = new Point2d();
		float rotation = getGPos(vector, point);
		GeometryUtil.turnVector(vector, rotation);
		point.add(vector);
		return point;
	}

	private float getGPos(Vector2d vector, Point2d point) {
		float result;
		if (this.parent != null) {
			result = this.parent.getGPos(vector, point);
		} else {
			result = this.body.getGlobalOrientation();
			point.set(this.body.getGlobalPosition().getX(), this.body.getGlobalPosition().getY());
			vector.set(0, 0);
		}
		vector.add(this.relativePosition);
		return result;
	}

	public FormationSlot getParent() {
		return this.parent;
	}

	public int getIndex() {
		return this.index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	@Override
	public int compareTo(FormationSlot otherSlot) {
		return (this.index - otherSlot.getIndex());
	}

}
